/**
 * 
 */
package com.ws.framework.remoteservice.core.protocal;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.logging.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author WSH
 *
 */
public class TransportOut extends MessageToByteEncoder<Object> {

	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Override
	protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
		byte[] result = serialize(msg);
		int length = result.length;
		out.writeInt(length);
		out.writeBytes(result);
		
	}
	
	private byte[] serialize(Object obj) {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		try {
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(obj);
			oos.flush();
			return bos.toByteArray();
		} catch (IOException e) {
			log.warning("Serialize to object occur error." + e);
			return null;
		} finally {
			if (null != bos) {
				try {
					bos.close();
				} catch (IOException e) {
				}
				
			}
			if (null != oos) {
				try {
					oos.close();
				} catch (IOException e) {
				}
			}
		}
	}
}
